package com.itcam.cm.manager.service.impl;

import com.itcam.cm.model.dto.system.SysMenuVo;
import com.itcam.cm.model.entity.system.SysMenu;

import java.util.ArrayList;
import java.util.List;

public class MenuHelper {
    public static List<SysMenu> buildTree(List<SysMenu> sysMenus) {
        List<SysMenu> tree = new ArrayList<>();
        // 分组处理
        for (SysMenu sysMenu : sysMenus ) {
            if(sysMenu.getParentId().longValue()==0){
                tree.add(findChildren(sysMenu,sysMenus));
            }
        }
        return tree;
    }

    private static SysMenu findChildren(SysMenu sysMenu, List<SysMenu> sysMenus) {
        // 遍历所有节点，判断是否为当前节点的子节点
        for (SysMenu child : sysMenus) {
            if(child.getParentId().longValue()==sysMenu.getId().longValue()){
                sysMenu.getChildren().add(findChildren(child,sysMenus));
            }
        }
        return sysMenu;
    }

    public static List<SysMenuVo> buildMenuVos(List<SysMenu> sysMenusTree) {
        List<SysMenuVo> sysMenuVosTree = new ArrayList<>();
        // 将sysMenu的tree转化成sysMenuVo的tree
        for (SysMenu sysMenu : sysMenusTree) {
            SysMenuVo sysMenuVo = new SysMenuVo();
            sysMenuVo.setName(sysMenu.getComponent());
            sysMenuVo.setTitle(sysMenu.getTitle());
            if(sysMenu.getChildren()!=null&sysMenu.getChildren().size()>0){
                sysMenuVo.setChildren(buildMenuVos(sysMenu.getChildren()));
            }
            sysMenuVosTree.add(sysMenuVo);
        }
        return sysMenuVosTree;
    }
}
